//
//  AsyncConnection.m
//  BeautyClother
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "AsyncConnection.h"
#import "Reachability.h"


@interface AsyncConnection ()<NSURLConnectionDataDelegate, NSURLConnectionDelegate>



@end

@implementation AsyncConnection

- (void)dealloc
{
    Block_release(_finishBlock);
    [_data release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.data = [NSMutableData data];
    }
    return self;
}


+ (instancetype)asyncConnection:(NSString *)urlStr parmaters:(NSDictionary *)parmaters block:(void(^)(NSData *data))block path:(NSString *)path
{
    

    AsyncConnection *asyn = [[AsyncConnection alloc]init];

    NSString *ss = @"";
    for (NSString *key  in parmaters) {
        if ([ss length] == 0) {
            ss = [NSString stringWithFormat:@"?%@=%@", key, [parmaters objectForKey:key]];
        }
        else
        {
            ss = [NSString stringWithFormat:@"%@&%@=%@", ss, key, [parmaters objectForKey:key]];
        }
    }
//    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
#pragma mark -
#pragma mark 本地缓存
    
    
    
    
   NSArray *addArr = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    asyn.path = [NSString stringWithFormat:@"%@%@%@",[addArr firstObject], @"/Caches/", path];
    NSLog(@"%@", asyn.path);
    
    
    
    urlStr = [NSString stringWithFormat:@"%@%@", urlStr, ss];
    NSLog(@"%@", urlStr);
    
    BOOL net = [AsyncConnection judgeConnect];
    if (net) {
        
    
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [asyn starConnection:urlStr];
    asyn.finishBlock = block;
    }else
    {
        NSLog(@"local");
        NSData *data = (NSMutableData *)[NSData dataWithContentsOfFile:asyn.path];
        [asyn.data appendData:data];
        block(asyn.data);
        

    }
    
    return [asyn autorelease];

}

+ (BOOL)judgeConnect
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus sta = [reach currentReachabilityStatus];
    if (sta == NotReachable) {
        return NO;
    }else{
        return YES;
    }
}



- (void)starConnection:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.finishBlock(self.data);
    [self.data writeToFile:self.path atomically:YES];
}




@end
